#include "XToken.h"

#include <cstring>
#include <ctype.h>

using namespace std;

XToken::XToken(const string& str) : mString( str ), mIndex( 0 ), mLastWordBegin( 0 ), mLastWordEnd( 0 ) {}

void XToken::reset()
{
  mIndex = 0;
  mLastWordBegin = 0;
  mLastWordEnd = 0;
}

string XToken::toString()
{
  return mString;
}

string XToken::getNextWord(const char endChars[])
{
    mLastSplitChars = endChars;
    if (mIndex >= mString.length()) {
    	return string();
    }

    mLastWordBegin = mIndex;
    mLastWordEnd = mString.length();
    char c;

    c = mString[mIndex];
    while (isspace(c) && mIndex < mString.length()) {
    	c = mString[++mIndex];
    }
    mLastWordBegin = mIndex;

    if (mLastWordBegin < mString.length()) {
      if (endChars == NULL || strlen(endChars) == 0) {
        mLastWordEnd = ++mIndex;
      } else {
	    c = mString[mIndex];
	    if (c == '\"' || c == '\'') {
          mLastWordBegin = ++mIndex;
          XToken token( mString.substr( mIndex ) );
          string value = token.getNextWord( string(1, c).c_str() );
          if ( value.empty() ) {
            mIndex = mString.length();
            mLastWordEnd = mLastWordBegin;
          } else {
            mLastWordEnd = mLastWordBegin + value.length();
            mIndex += value.length() + 1;
          }
	    } else {
          while (strchr(endChars, c) == NULL && mIndex < mString.length()) {
            c = mString[++mIndex];
          }
          mLastWordEnd = mIndex;
          if ( mLastWordEnd == mLastWordBegin ) {
            mIndex = ++mLastWordEnd;
          }
        }
      }
    }

    return mString.substr(mLastWordBegin, (mLastWordEnd - mLastWordBegin));
}

string XToken::getLastWord()
{
  return mString.substr(mLastWordBegin, (mLastWordEnd - mLastWordBegin));
}

string XToken::getParsedString()
{
  return mString.substr( 0, mIndex );
}

string XToken::getLastSplitChars()
{
  return mLastSplitChars;
}

